import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/sp_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';
import 'package:fsuper/fsuper.dart';
import 'package:provide/provide.dart';
import 'package:qr_utils/qr_utils.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_map.dart';

class MinePage extends StatefulWidget {
  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends StateWithLifecycle<MinePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  User user;
  int fansNum = 0;
  int followNum = 0;
  double profit = 0.00;

  EasyRefreshController _refreshController = EasyRefreshController();

  Future _initData() async {
    Http.get(Api.URL_INFO, successCallBack: (data) {
      SpUtils.put(SpUtils.SP_USER, data);
      setState(() {
        Comm.isLogin = true;
        user.update(User.fromJson(json.decode(data)));
      });
      String url = "${Api.URL_USER_NUM}?userId=${user.userId}";
      Http.get(url, successCallBack: (data) {
        setState(() {
          fansNum = json.decode(data)["fansNum"];
          followNum = json.decode(data)["followNum"];
          profit = json.decode(data)["profit"];
        });
        _refreshController.finishRefresh();
      }, errorCallBack: (error) {
        _refreshController.finishRefresh();
      });
    }, errorCallBack: (error) {
      setState(() {
        Comm.isLogin = false;
      });
      _refreshController.finishRefresh();
    });
  }

  @override
  void onResume() {
    super.onResume();
    _initData();
  }

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    if (null != user && null != user.userId) {
      Comm.isLogin = true;
    }
    return Scaffold(
      appBar: AppBar(
        leading: _scanWidget(),
        elevation: 0.0,
        backgroundColor: Theme.of(context).canvasColor,
      ),
      body: EasyRefresh.custom(
          onRefresh: () => _initData(),
          enableControlFinishRefresh: true,
          header: _headerWidget(),
          controller: _refreshController,
          slivers: <Widget>[
            SliverList(
                delegate: SliverChildListDelegate([
              Column(
                children: <Widget>[
                  _userWidget(),
                  _assetsWidget(),
                  SizedBox(height: 10),
                  _vipWidget(),
                  _dividerWidget(),
                  _walletWidget(),
                  SizedBox(height: 10),
                  _adviceWidget(),
                  _dividerWidget(),
                  _shareWidget(),
                  _dividerWidget(),
                  _settingWidget(),
                  SizedBox(height: 20),
                ],
              )
            ]))
          ]),
    );
  }

  ///单边分割线
  Widget _dividerWidget() {
    return Container(
      height: 1,
      margin: EdgeInsets.only(left: 10),
      color: Color(0xffF2F2F2),
    );
  }

  ///用户信息
  Widget _userWidget() {
    Widget _headWidget = GestureDetector(
      child: Container(
        width: 56,
        height: 56,
        margin: EdgeInsets.only(left: 10, right: 10),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(28),
          child: CachedNetworkImage(
            imageUrl: Api.getUrl(user.imgUrl),
            fit: BoxFit.cover,
            errorWidget: (context, url, error) =>
                Image.asset(Comm.IMG_DEFAULT, fit: BoxFit.cover),
          ),
        ),
      ),
      onTap: () {
        if (!Comm.isLogin || null == user || null == user.userId) {
          return;
        }
        Routers.router.navigateTo(
            context, '${Routers.PAGE_USERINFO}?userId=${user.userId}',
            transition: TransitionType.inFromRight);
      },
    );
    Color vipColor = Colors.grey;
    if (null != user && user.vip == 1) {
      vipColor = Color(0xffFFCE40);
    }
    Widget _nickWidget = Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Text(
                user.userName ?? "",
                style: TextStyle(
                  fontSize: 22,
                  fontWeight: FontWeight.w400,
                ),
              ),
              Image.asset(
                Comm.IMG_IC_VIP,
                width: 18,
                height: 18,
                color: vipColor,
              )
            ],
          ),
          Row(
            children: <Widget>[
              GestureDetector(
                child: Text("关注", style: TextStyle(color: Color(0xff999999))),
                onTap: () {
                  String url =
                      "${Routers.PAGE_USER_LIST}?type=1&userId=" + user.userId;
                  Routers.router.navigateTo(context, url,
                      transition: TransitionType.inFromRight);
                },
              ),
              SizedBox(width: 10),
              Text("$followNum"),
              SizedBox(width: 20),
              GestureDetector(
                child: Text("粉丝", style: TextStyle(color: Color(0xff999999))),
                onTap: () {
                  String url =
                      "${Routers.PAGE_USER_LIST}?type=2&userId=" + user.userId;
                  Routers.router.navigateTo(context, url,
                      transition: TransitionType.inFromRight);
                },
              ),
              SizedBox(width: 10),
              Text("$fansNum"),
            ],
          ),
        ],
      ),
    );

    Widget _loginWidget = GestureDetector(
      child: Container(
        child: Text(
          "登录/注册",
          style: TextStyle(
            fontSize: 22,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
      onTap: () {
        Routers.router.navigateTo(context, Routers.PAGE_LOGIN,
            transition: TransitionType.inFromRight);
      },
    );
    return Row(children: <Widget>[
      _headWidget,
      Comm.isLogin ? _nickWidget : _loginWidget,
    ]);
  }

  ///资产卡片
  Widget _assetsWidget() {
    //收益展示
    Widget _shouyiWiget = FSuper(
      width: double.infinity,
      text: "总收益：￥$profit",
      margin: EdgeInsets.all(10),
      textSize: 16,
      textAlignment: Alignment.centerLeft,
      child1: Text("查看", style: TextStyle(color: Colors.grey)),
      child1Alignment: Alignment.centerRight,
      child1Margin: EdgeInsets.only(right: 16),
      child2: Image.asset(
        Comm.IMG_ARROW_RIGHT,
        width: 18,
        height: 14,
        color: Color(0xff777777),
      ),
      child2Alignment: Alignment.centerRight,
      onChild1Click: () {
        String url = '${Routers.PAGE_TRADE}?dirType=01';
        Routers.router.navigateTo(
          context,
          url,
          transition: TransitionType.inFromRight,
        );
      },
    );

    //分割线
    Widget _dividerWidget = Container(
      height: 1,
      margin: EdgeInsets.only(left: 10, right: 10),
      color: Color(0xfff2f2f2),
    );

    //tab显示
    Widget _tabWidget = Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        GestureDetector(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset(Comm.IMG_ORDER, width: 28, height: 28),
              Text("我买到的", style: TextStyle(fontSize: 16)),
            ],
          ),
          onTap: () {
            if (!Comm.isLogin) {
              Toast.show("请先登录~");
              return;
            }
            String url = "${Routers.PAGE_ORDER}?type=01";
            Routers.router.navigateTo(context, url,
                transition: TransitionType.inFromRight);
          },
        ),
        GestureDetector(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset(Comm.IMG_SALE, width: 28, height: 28),
              Text("我卖出的", style: TextStyle(fontSize: 16)),
            ],
          ),
          onTap: () {
            if (!Comm.isLogin) {
              Toast.show("请先登录~");
              return;
            }
            String url = "${Routers.PAGE_ORDER}?type=02";
            Routers.router.navigateTo(context, url,
                transition: TransitionType.inFromRight);
          },
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(Comm.IMG_COLLECT, width: 28, height: 28),
            Text("我的收藏", style: TextStyle(fontSize: 16)),
          ],
        ),
      ],
    );
    return Card(
      margin: EdgeInsets.all(10),
      elevation: 4,
      child: Column(
        children: <Widget>[
          _shouyiWiget,
          _dividerWidget,
          Container(child: _tabWidget, padding: EdgeInsets.all(10)),
        ],
      ),
    );
  }

  ///扫一扫控件
  Widget _scanWidget() {
    return GestureDetector(
      child: Container(
        width: 36,
        height: 36,
        alignment: Alignment.center,
        child: Image.asset(
          Comm.IMG_QR_SCAN,
          width: 20,
          height: 20,
        ),
      ),
      onTap: () async {
        String result = await QrUtils.scanQR;
        if (result.startsWith("USER")) {
          Routers.router.navigateTo(
              context, '${Routers.PAGE_USERINFO}?userId=$result',
              transition: TransitionType.inFromRight);
        } else {
          Toast.show("无效二维码");
        }
      },
    );
  }

  ///充值会员
  Widget _vipWidget() {
    return GestureDetector(
      child: Container(
        color: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10, right: 10),
        child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
          Text('会员中心', style: TextStyle(fontSize: 16)),
          Expanded(child: Container()),
          Image.asset(Comm.IMG_ARROW_RIGHT, width: 18, height: 18)
        ]),
      ),
      onTap: () {
        if (!Comm.isLogin) {
          Toast.show("请先登录");
          return;
        }
        Routers.router.navigateTo(
          context,
          Routers.PAGE_MEMBER,
          transition: TransitionType.inFromRight,
        );
      },
    );
  }

  ///我的钱包
  Widget _walletWidget() {
    return GestureDetector(
      child: Container(
        color: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10, right: 10),
        child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
          Text('我的钱包', style: TextStyle(fontSize: 16)),
          Expanded(child: Container()),
          Image.asset(Comm.IMG_ARROW_RIGHT, width: 18, height: 18)
        ]),
      ),
      onTap: () {
        if (!Comm.isLogin) {
          Toast.show("请先登录");
          return;
        }
        Routers.router.navigateTo(
          context,
          Routers.PAGE_WALLET,
          transition: TransitionType.inFromRight,
        );
      },
    );
  }

  ///意见反馈
  Widget _adviceWidget() {
    return GestureDetector(
      child: Container(
        color: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10, right: 10),
        child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
          Text('意见反馈', style: TextStyle(fontSize: 16)),
          Expanded(child: Container()),
          Image.asset(Comm.IMG_ARROW_RIGHT, width: 18, height: 18)
        ]),
      ),
      onTap: () {
        Routers.router.navigateTo(context, Routers.PAGE_ADVISE,
            transition: TransitionType.inFromRight);
      },
    );
  }

  ///设置
  Widget _settingWidget() {
    return GestureDetector(
      child: Container(
        height: 48,
        padding: EdgeInsets.only(left: 10, right: 10),
        alignment: Alignment.centerLeft,
        color: Theme.of(context).cardColor,
        child: Row(children: <Widget>[
          Text("设置", style: TextStyle(fontSize: 16)),
          Expanded(child: Container()),
          Image.asset(Comm.IMG_ARROW_RIGHT, width: 18, height: 18)
        ]),
      ),
      onTap: () {
        Routers.router.navigateTo(context, Routers.PAGE_MINE_SETTING,
            transition: TransitionType.inFromRight);
      },
    );
  }

  ///分享
  Widget _shareWidget() {
    return GestureDetector(
      child: Container(
        height: 48,
        padding: EdgeInsets.only(left: 10, right: 10),
        alignment: Alignment.centerLeft,
        color: Theme.of(context).cardColor,
        child: Row(children: <Widget>[
          Text("我要分享", style: TextStyle(fontSize: 16)),
          Expanded(child: Container()),
          Image.asset(Comm.IMG_ARROW_RIGHT, width: 18, height: 18)
        ]),
      ),
      onTap: () {
        SSDKMap params = SSDKMap()
          ..setGeneral(
            "单片机助手",
            "单片机爱好者学习交流平台",
            [""],
            Api.getUrl("/static/app_logo.png"),
            null,
            "http://fir.sxjksj.cn/b5p7",
            "http://fir.sxjksj.cn/b5p7",
            null,
            null,
            null,
            SSDKContentTypes.webpage,
          );
        SharesdkPlugin.showMenu(null, params, null);
      },
    );
  }

  ClassicalHeader _headerWidget() {
    return ClassicalHeader(
        refreshText: "下拉可刷新",
        refreshReadyText: "释放立即刷新",
        refreshingText: "正在刷新...",
        refreshedText: "刷新完成",
        showInfo: false,
        textColor: Color(0xff666666));
  }
}
